package com.longxi.tianjintianbao.ui.presenter.rectification;

import android.content.Intent;
import android.view.View;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.listener.RectificationListListener;
import com.longxi.tianjintianbao.listener.SelectRectificationItemListener;
import com.longxi.tianjintianbao.model.Personnel;
import com.longxi.tianjintianbao.model.rectification.RectificationItem;
import com.longxi.tianjintianbao.model.rectification.RectificationList;
import com.longxi.tianjintianbao.ui.activity.rectification.RectificationActivity;
import com.longxi.tianjintianbao.ui.adapter.multitype.RectificationItemViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.RectificationListViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.dialog_fragment.RectificationStateDialogFragment;
import com.longxi.tianjintianbao.ui.view.rectification.IRectificationDetailAtView;
import com.longxi.tianjintianbao.utils.MyUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class RectificationDetailAtPresenter extends BasePresenter<IRectificationDetailAtView> {

    private MultiTypeAdapter adapter;
    private Items items;

    RectificationList rectificationList = null;//传递过来的详情值
    private String billid = "";
    public List<Personnel> personnels = new ArrayList<>();//存放员工的数据 用于多选

    public RectificationDetailAtPresenter(BaseActivity context) {
        super(context);
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            adapter.register(RectificationList.class, new RectificationListViewBinder(rectificationListListener));
            adapter.register(RectificationItem.class, new RectificationItemViewBinder(selectRectificationItemListener));
            getView().getRvContent().setAdapter(adapter);
        }
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
        billid = intent.getStringExtra(AppConst.BILLID);
        mContext.setTitle("详情");
        mContext.setTvLeft(MyUtils.getString(R.string.back));
        mContext.setResult(mContext.RESULT_OK);
    }

    public void getRectification(){
        JSONObject object = new JSONObject();
        try {
            object.put("billid", billid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().getRectification(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<RectificationList>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<RectificationList> result) {
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }

                if(result.getData().size() == 0){
                    MyUtils.showToast(MyUtils.getString(R.string.data_error));
                    return;
                }
                rectificationList = result.getData().get(0);
                items = new Items();
                items.add(rectificationList);
                adapter.setItems(items);
                getRectificationItem();
            }
        });
    }

    /**
     * 显示开始结束按钮
     */
    private void showBtn() {
        if(rectificationStateDialogFragment != null){
            rectificationStateDialogFragment.dismiss();
        }

        switch (rectificationList.getState()) {
            case "未完成":
                getView().getBtnLogin().setText("结束");
                getView().getBtnLogin().setVisibility(View.VISIBLE);
                break;
            case "已完成":
                getView().getBtnLogin().setVisibility(View.GONE);
//                getView().getBtnLogin().setText("结束整改");
//                getView().getBtnLogin().setVisibility(View.VISIBLE);
                break;
            default:
                getView().getBtnLogin().setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 获取整改项
     */
    public void getRectificationItem(){
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("billid", billid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().getRectificationItem(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<RectificationItem>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<RectificationItem> result) {
                items.addAll(result.getData());
                adapter.setItems(items);
                adapter.notifyDataSetChanged();
                showBtn();
                mContext.setResult(mContext.RESULT_OK);
            }
        });
    }

    /**
     * 添加进度
     */
    public void goFinshOrChange() {
        switch (rectificationList.getState()) {
            case "未完成":
                showQualityStateDialogFragment();
                break;
            case "已完成":
//                saveRectificationState("1", "", "");
                break;
            default:
                break;
        }
    }

    RectificationStateDialogFragment rectificationStateDialogFragment;
    public void showQualityStateDialogFragment() {
        rectificationStateDialogFragment = new RectificationStateDialogFragment();
        rectificationStateDialogFragment.show(mContext.getFragmentManager(), "QualityStateDialogFragment");
    }

    /**
     * 品质检查完成
     */
    public void saveRectificationState(String finishremark){

        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("billid", billid);
            object.put("finishremark", finishremark);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().saveRectificationState(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                getRectification();
            }
        });
    }

    public List<Personnel> getPersonnels(){
        if(personnels.size() == 0){
            Personnel personnel = new Personnel();
            personnel.setUserid("");
            personnel.setUsername("");
            personnels.add(personnel);
        }
        return personnels;
    }

    /**
     * 删除数据
     * @return
     */
    public boolean deletePersonnels(Personnel personnel) {
        for (int i = 0; i < personnels.size(); i++)  {
            if (personnel.getUserid().equals(personnels.get(i).getUserid())) {
                personnels.remove(i);
                return true;
            }
        }
        return false;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == AppConst.IntentRequstCode.ACTIVITY_UPDATE_REPAIR_CONTENT){
            getRectification();
            mContext.setResult(mContext.RESULT_OK);
        }
    }

    RectificationListListener rectificationListListener = new RectificationListListener() {
        @Override
        public void onSuccess(RectificationList rectificationList) {
        }
    };
    SelectRectificationItemListener selectRectificationItemListener = new SelectRectificationItemListener() {
        @Override
        public void onSuccess(RectificationItem rectificationItem) {
            Intent mainIntent = new Intent(mContext, RectificationActivity.class);
            mainIntent.putExtra(RectificationAtPresenter.RECTIFICATIONITEM,rectificationItem);
            mContext.startActivityForResult(mainIntent, AppConst.IntentRequstCode.ACTIVITY_UPDATE_REPAIR_CONTENT);
        }
    };

    public void onDestroy() {
        rectificationListListener = null;
        selectRectificationItemListener = null;
    }
}
